package servlet.musicBoxe;

import Dao.MusicBoxDAO;
import pojo.MusicBox;
import pojo.User;
import service.MusicBoxService;
import service.impl.MusicBoxServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
// 查询musicBoxe视图实体类
@WebServlet("/musicBoxe")
public class MusicBoxesServlet extends HttpServlet {
    MusicBoxService musicBoxService = new MusicBoxServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 分页查询
        Integer startIndex = Integer.valueOf(req.getParameter("startIndex"));
        Integer targetTotal = Integer.valueOf(req.getParameter("targetTotal"));
        Integer pageSize = targetTotal;  // 每页显示的条目数
        User currentUser = (User) req.getSession().getAttribute("user");
        int recipientId = currentUser.getUserId();
        List<MusicBox> musicBoxes = musicBoxService.getSongRequestDetails(recipientId, startIndex, pageSize);
        if (musicBoxes == null){
            req.getRequestDispatcher("/musicBoxes.jsp").forward(req, resp);
            return;
        }
        Integer totalCount = musicBoxes.size();
        Integer totalPages = (int) Math.ceil(totalCount / (double) pageSize);
        req.getSession().setAttribute("musicBoxes", musicBoxes);
        // 将用户列表、总页数和当前页码等信息存储在请求域中
        req.getSession().setAttribute("totalCount", totalCount);
        req.getSession().setAttribute("totalPages", totalPages);
        req.getSession().setAttribute("targetTotal", targetTotal);
        req.getSession().setAttribute("currentPage", (startIndex / targetTotal) + 1);  // 当前页码，假设startIndex从0开始

        req.getRequestDispatcher("/musicBoxes/musicBoxes.jsp").forward(req, resp);

    }
}
